package com.leyou.order.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.leyou.common.auth.pojo.UserHolder;
import com.leyou.common.auth.pojo.UserInfo;
import com.leyou.common.pojo.PageResult;
import com.leyou.common.utils.BeanHelper;
import com.leyou.order.dto.OrderVO;
import com.leyou.order.mapper.OrderDetailMapper;
import com.leyou.order.mapper.OrderMapper;
import com.leyou.order.pojo.Order;
import com.leyou.order.pojo.OrderDetail;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
public class OrderCenterService extends ServiceImpl<OrderMapper, Order> {

    @Autowired
    private OrderDetailMapper detailMapper;

    @Autowired(required = false)
    private OrderMapper orderMapper;



    /**
     * 分页查询你的订单
     * TODO
     * [status, num, rows]
     * @return {icu.boxuegu.common.pojo.PageResult<icu.boxuegu.order.DTO.OrderVO>}
     * @BigTingBro
     * @2020/11/16 16:17
     */
    public PageResult<OrderVO> findOrderByUserId(Integer status, Integer num , Integer rows) {
        //线程中取出任务
        UserInfo user = UserHolder.getUser();
        //构建查询条件
        QueryWrapper<Order> rapper = new QueryWrapper<>();
        rapper.eq("user_id", user.getId());
        //订单状态是否为空
        if (status!=null){
            rapper.eq("status",status);
        }
        //获取分页对象
        IPage<Order> page = page(new Page<>(num, rows), rapper);
        //转换为VO对象
        List<OrderVO> orderVOS = BeanHelper.copyWithCollection(page.getRecords(), OrderVO.class);
        //遍历添加OrderDetail
        orderVOS.forEach(orderVO -> orderVO.setDetailList(detailMapper.selectList(new QueryWrapper<OrderDetail>().eq("order_id",orderVO.getOrderId()))));


        return new PageResult<OrderVO>(page.getTotal(),page.getPages(),orderVOS);
    }
}
